package com.example.controller;

import com.example.comm.Result;
import com.example.controller.request.LiteratureRequest;
import com.example.dao.LiteratureDao;
import com.example.dao.LiteratureSpecification;
import com.example.entity.Literature;

import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("/literature")
public class LiteratureController {
    @Autowired
    private LiteratureDao literatureDao;

    @GetMapping("/getAll")
    public Result getAll() {
        return Result.success(literatureDao.findAll());
    }

    @GetMapping("/page")
    public Result page(LiteratureRequest literatureRequest) {
        Pageable pageable = PageRequest.of(literatureRequest.getPageNum() - 1, literatureRequest.getPageSize(), Sort.by(Sort.Direction.DESC, "id"));

        Specification<Literature> specification = new LiteratureSpecification(literatureRequest);
        Page<Literature> page = literatureDao.findAll(specification, pageable);
        return Result.success(page);
    }

    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Long id) {
        literatureDao.deleteById(id);
        return Result.success();
    }

    @GetMapping("/getLda/{id}")
    public Result test1(@PathVariable Long id) throws InterruptedException {
        Optional<Literature> literature = literatureDao.findById(id);
//        System.out.println(literature);

        Map<String, String> data = new HashMap<>();
        data.put("keyword", literature.get().getKeywords());
        data.put("abstract", literature.get().getAbstract1());
        // 创建一个CountDownLatch实例，用于等待响应结果
        CountDownLatch latch = new CountDownLatch(1);
// 创建一个AtomicReference实例，用于存储响应结果
        AtomicReference<String> result = new AtomicReference<>();
        WebClient.create()
                .post()
                .uri("http://127.0.0.1:5000/test_post")
                .body(BodyInserters.fromValue(data))
                .retrieve()
                .bodyToMono(String.class)
                // 订阅响应结果
                .subscribe(response -> {
                    // 在这里处理响应结果
                    result.set(response);
                    // 递减计数器
                    latch.countDown();
                });
        // 等待计数器归零
        latch.await();
// 打印响应结果
        System.out.println(result.get());
        return Result.success(StringEscapeUtils.unescapeJava(result.get()));
    }


    // 尝试转发请求到flask
    @GetMapping("/test")
    public Result test() throws InterruptedException {
        // 异步处理
        // 创建一个CountDownLatch实例，用于等待响应结果
        CountDownLatch latch = new CountDownLatch(1);
// 创建一个AtomicReference实例，用于存储响应结果
        AtomicReference<String> result = new AtomicReference<>();

// 使用WebClient发送GET请求
        WebClient.create()
                .get()
                .uri("http://127.0.0.1:5000")
                .retrieve()
                .bodyToMono(String.class)
                // 订阅响应结果
                .subscribe(response -> {
                    // 在这里处理响应结果
                    result.set(response);
                    // 递减计数器
                    latch.countDown();
                });

// 等待计数器归零
        latch.await();
// 打印响应结果
        System.out.println(result.get());
        return Result.success(result);
    }
}
